package com.woniuxy.services.impl;

import com.woniuxy.daos.TbPermissionDao;
import com.woniuxy.daos.TbUserRoleDao;
import com.woniuxy.entitys.TbPermission;
import com.woniuxy.services.PermissionService;
import com.woniuxy.utils.JWTUtils;
import com.woniuxy.utils.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PerServiceImpl implements PermissionService {
    @Autowired
    private JWTUtils jwtUtils;
    @Autowired
    private TbPermissionDao tbPermissionDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TbUserRoleDao tbUserRoleDao;
    @Override
    public List<TbPermission> getPerMenuTree(String token) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String username = jwtUtils.getUsername(token);
        LoginUser o = (LoginUser) valueOperations.get("user:" + username);//得到loginuser
        Integer uid = o.getUser().getUid();
        Integer rid = tbUserRoleDao.selectByUid(uid).getRid();
        List<TbPermission> tbPermissions = tbPermissionDao.getAll(rid);//查询所有菜单
        List<TbPermission> menuPers = getMenuPers(tbPermissions,0);//查询所有菜单
        return menuPers;
    }

    @Override
    public List<TbPermission> getAll(Integer rid) {
        return tbPermissionDao.getAll(rid);
    }

    private List<TbPermission> getMenuPers(List<TbPermission> Permissions, int parentId) {
        List<TbPermission> list = new ArrayList<TbPermission>();
        for (TbPermission permission : Permissions) {
            //寻找一级权限
            if (permission.getPid() == parentId) {
                recurseFn(Permissions, permission);
                list.add(permission);
            }
        }
        return list;

    }

    private void recurseFn(List<TbPermission> Permissions, TbPermission permission) {
        List<TbPermission> children = getChild(Permissions, permission);
        permission.setChildren(children);
        //对所有子权限进行递归
        for(TbPermission child:children){
            if(getChild(Permissions,child).size()>0){
                recurseFn(Permissions,child);
            }

        }}

    private List<TbPermission> getChild(List<TbPermission> Permissions,TbPermission parentPer){
        List<TbPermission> children = new ArrayList<TbPermission>();
        for(TbPermission permission:Permissions){
            if(permission.getPid()==parentPer.getId()){
                children.add(permission);}
        }
        return children;
    }

}
